package com.itheima.mm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mm.mapper.ArticlesMapper;

import com.itheima.mm.pojo.HmArticles;
import com.itheima.mm.pojo.PageResult;
import com.itheima.mm.dto.Result;
import com.itheima.mm.service.ArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticlesServiceImpl extends ServiceImpl<ArticlesMapper, HmArticles> implements ArticlesService {

    @Autowired
    private ArticlesMapper articlesMapper;

    @Override
    public PageResult findPage(String keyword, Integer state, Integer page, Integer pagesize) {
        IPage<HmArticles> p = new Page<>(page, pagesize);
        LambdaQueryWrapper<HmArticles> wrapper = new LambdaQueryWrapper<>();
        if (keyword != null && keyword !="") {
            wrapper.like(HmArticles::getTitle, keyword);
            System.out.println(keyword);
        }
        if (state != null) {
            wrapper.eq(HmArticles::getState, state);
        }

        IPage<HmArticles> articlesIPage = articlesMapper.selectPage(p, wrapper);


        return new PageResult(articlesIPage.getTotal()
                , articlesIPage.getSize()
                , articlesIPage.getPages()
                , articlesIPage.getCurrent()
                , articlesIPage.getRecords());
    }

    @Override
    public Result updateState(Integer id, Integer state) {
        LambdaUpdateWrapper<HmArticles> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(HmArticles::getState, state);
        wrapper.eq(HmArticles::getId, id);
        int update = articlesMapper.update(null, wrapper);
        if (update <= 0) {
            return new Result(false);
        }
        return new Result(true);
    }

    @Override
    public Result rm(Integer id) {
        int delete = articlesMapper.deleteById(id);
        if (delete <= 0) {
            return new Result(false);
        }
        return new Result(true);
    }

    @Override
    public Result put(Integer id, HmArticles hmArticles) {
        int i = articlesMapper.updateById(hmArticles);
        if (i <= 0) {
            return new Result(false);
        }
        return new Result(true);
    }

    @Override
    public void add(HmArticles hmArticles) {
        articlesMapper.insert(hmArticles);
    }

    @Override
    public HmArticles details(Integer id) {
        return articlesMapper.selectById(id);
    }
}
